package cn.jingzhuan.fm.ui.fragment

import android.content.Context
import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.design.widget.BottomSheetDialogFragment
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.AndroidSupportInjection
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject

abstract class  BaseBindingBottomSheetDialogFragment<T : ViewDataBinding> : BottomSheetDialogFragment(), HasSupportFragmentInjector {

    protected lateinit var mBinding: T
    protected var mProgressDialog: QMUITipDialog? = null
    private var mAfterDataBindListener: OnAfterDataBindListener? = null


    @Inject
    lateinit var childFragmentInjector: DispatchingAndroidInjector<Fragment>

    override fun supportFragmentInjector(): AndroidInjector<Fragment> {
        return childFragmentInjector
    }


    override fun onCreateView(inflater: LayoutInflater,
                              container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        AndroidSupportInjection.inject(this)
        val rootView = inflater.inflate(getLayoutId(), container, false)
        mBinding = createDataBinding(rootView)!!
        this.onDataBind(savedInstanceState, mBinding)

        if (mAfterDataBindListener != null) {
            mAfterDataBindListener?.onDataBind(context)
        }
        return rootView
    }

    private fun createDataBinding(rootView: View): T? {
        return DataBindingUtil.bind(rootView)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding.unbind()
    }

    protected abstract fun onDataBind(savedInstanceState: Bundle?, binding: T)

    @LayoutRes
    protected abstract fun getLayoutId(): Int

    protected fun showProgress(msg: String) {
        if (context != null) {
            mProgressDialog?.dismiss()

            mProgressDialog = QMUITipDialog.Builder(context)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord(msg)
                    .create()
            mProgressDialog?.setCancelable(true)
            mProgressDialog?.show()
        }
    }

    protected fun showProgress() {
        showProgress("正在加载")
    }

    protected fun hideProgress() {
        if (mProgressDialog != null && mProgressDialog!!.isShowing) {
            mProgressDialog?.dismiss()
        }
    }


    fun setAfterDataBindListener(afterDataBindListener: OnAfterDataBindListener) {
        this.mAfterDataBindListener = afterDataBindListener
    }

    interface OnAfterDataBindListener {
        fun onDataBind(context: Context?)
    }

}
